package cq.zhcqk.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dou361.dialogui.DialogUIUtils;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zzhoujay.richtext.RichText;

import org.apache.http.Header;
import org.json.JSONObject;

import java.util.Map;

import cq.zhcqk.R;
import cq.zhcqk.app;
import cq.zhcqk.base.BaseActivity;
import cq.zhcqk.util.CheckLogin;
import cq.zhcqk.util.Common;
import cq.zhcqk.util.GsonUtil;
import cq.zhcqk.util.JsUtil;
import cq.zhcqk.util.StringUtil;
import cq.zhcqk.util.WebViewHeader;
import cq.zhcqk.util.x5.X5WebView;

/**
 * Created by zhangle on 2017/12/3.
 */
public class ListDetailSampleActivity extends BaseActivity implements View.OnClickListener{
    private TextView title;
    private TextView num;
    private TextView time;
    private TextView content_text;
    private TextView slug;
    private LinearLayout detail;
    private RichText richText;
    private String cid;
    private int slug_num = 0;
//    private WebView webTest;

    private X5WebView tc_webview;
    private String url;
    @Override
    protected void initView() {
        setContentView(R.layout.activity_list_detail_sample);
        initBack();
        title = (TextView) findViewById(R.id.title);
        num = (TextView) findViewById(R.id.num);
        time = (TextView) findViewById(R.id.time);
        content_text = (TextView) findViewById(R.id.content_text);
        slug = (TextView) findViewById(R.id.slug);
        detail = (LinearLayout) findViewById(R.id.detail_lay);
//        webTest = (WebView)findViewById(R.id.webTest);
        slug.setOnClickListener(this);
        tc_webview = (X5WebView) findViewById(R.id.tc_webview);
        url = getIntent().getStringExtra("url");
    }

    @Override
    protected void initData() {
        cid = getIntent().getStringExtra("cid");
//        setWeb();
//        getDetail();
//        WebViewHeader.setHeaderAndLoad(webTest,Common.URL+"/blog/open/post/"+cid);
        if(StringUtil.isNull(url)){
            WebViewHeader.setHeaderAndLoadX5(tc_webview,Common.URL+"/blog/open/post/"+cid);
        }else{
            WebViewHeader.setHeaderAndLoadX5(tc_webview,url);
        }
        show();
    }

    public void show(){
        if(tc_webview != null)
        {
            com.tencent.smtt.sdk.WebSettings settings = tc_webview.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setBuiltInZoomControls(true);
            settings.setLoadWithOverviewMode(true);
            settings.setUseWideViewPort(true);
            settings.setDatabaseEnabled(true);
            settings.setBuiltInZoomControls(false);
            settings.setSupportZoom(false);
            settings.setDisplayZoomControls(false);

            tc_webview.addJavascriptInterface(new JavascriptInterface(context), "imagelistner");
            tc_webview.setWebViewClient(new com.tencent.smtt.sdk.WebViewClient()
            {
                @Override
                public void onPageFinished(com.tencent.smtt.sdk.WebView webView, String s) {
                    super.onPageFinished(webView, s);
                    DialogUIUtils.dismiss(buildBean);
                    JsUtil.addX5ImageClickListner(tc_webview);
                }

                @Override
                public void onPageStarted(com.tencent.smtt.sdk.WebView webView, String s, Bitmap bitmap) {
                    super.onPageStarted(webView, s, bitmap);
                    buildBean.show();
                }
            });
        }
    }

    public class JavascriptInterface {

        private Context context;

        public JavascriptInterface(Context context) {
            this.context = context;
        }
        @android.webkit.JavascriptInterface
        public void openImage(String img) {
            System.out.println(img);

            Intent intent = new Intent();
            intent.putExtra("image", img);
            intent.setClass(context, ShowWebImageActivity.class);
            context.startActivity(intent);
            System.out.println(img);
        }
    }

    private void initBack(){
        ImageView back = (ImageView) findViewById(R.id.header_back);
        TextView title = (TextView) findViewById(R.id.header_text);
        title.setText("和美磁器口");
        back.setOnClickListener(this);
    }

//    public void setWeb(){
//        WebSettings settings = webTest.getSettings();
//        settings.setJavaScriptEnabled(true);
//        settings.setBuiltInZoomControls(true);
//        settings.setLoadWithOverviewMode(true);
//        settings.setUseWideViewPort(true);
//        settings.setDatabaseEnabled(true);
//        settings.setBuiltInZoomControls(false);
//        settings.setSupportZoom(false);
//        settings.setDisplayZoomControls(false);
//
//        if(webTest != null)
//        {
//            webTest.setWebViewClient(new WebViewClient()
//            {
//                @Override
//                public void onPageFinished(WebView view,String url)
//                {
//                    DialogUIUtils.dismiss(buildBean);
//                }
//
//                @Override
//                public void onPageStarted(WebView view, String url, Bitmap favicon) {
//                    super.onPageStarted(view, url, favicon);
//                    buildBean.show();
//                }
//            });
//        }
//    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.header_back:
                finish();
                break;
            case R.id.slug:
                if(!app.isLogin){
                    Toast.makeText(context,"请先登录",Toast.LENGTH_SHORT).show();
                    context.startActivity(new Intent(context, LoginActivity.class));
                    overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                    return;
                }
                buildBean.show();
                shouChang();
                break;
        }
    }

    public void setSlug(){
        slug.setText(slug_num+"人收藏");
    }

    private String relaceUrl(String content){
        String info = content.replace("<img src=\"/","<img src=\""+Common.URL+"/");
        System.out.println(info);
        return info;
    }

    private void getDetail(){
        RequestParams params = new RequestParams();
        params.add("cid",cid);
        httpClient.post(Common.URL+Common.NEWS_DETAIL,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccess："+response);
                Map<String, Object> map = GsonUtil.GsonToMaps(response+"");
                if(map != null && map.size()>0){
                    Map<String, Object> mapData = (Map<String, Object>) map.get("data");
                    if(mapData != null && mapData.size()>0){
                        richText = RichText.from(relaceUrl(mapData.get("content")+"")).into(content_text);
                        slug_num = StringUtil.stringToInt(mapData.get("slug")+"");
                        title.setText(mapData.get("title")+"");
                        num.setText(StringUtil.stringToInt(mapData.get("hits")+"")+"");
                        time.setText(mapData.get("time")+"");
                        setSlug();
                        detail.setVisibility(View.VISIBLE);

//                        webTest.loadUrl(Common.URL+"/blog/open/post/"+cid);
//                        WebViewHeader.setHeaderAndLoad(webTest,Common.URL+"/blog/open/post/"+cid);
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUIUtils.dismiss(buildBean);
            }
        });
    }

    private void shouChang(){
        RequestParams params = new RequestParams();
        params.add("cid",cid);
        httpClient.post(Common.URL+Common.NEWS_DCT,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccess："+response);
                slug_num++;
                setSlug();
                Toast.makeText(context,"收藏成功",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                System.out.println("onFailure："+errorResponse);
                CheckLogin.checkLogin(context,errorResponse+"");
//                Toast.makeText(context,"发布评论失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                Toast.makeText(context,"收藏失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUIUtils.dismiss(buildBean);
            }
        });
    }
    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (this.tc_webview != null) {
            tc_webview.setVisibility(View.GONE);
            tc_webview.removeAllViews();
            tc_webview.destroy();
        }
    }
}
